#include "TCP.h"

int TCP_server_create()
{
    int sockfd;
    struct sockaddr_in s_addr;
    socklen_t len;
    len=sizeof(struct sockaddr);
    sockfd=socket(AF_INET,SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC,0);
    if(sockfd<0)
    {
        perror("socket error\n");
        exit(1);
    }
    s_addr.sin_family=AF_INET;
    s_addr.sin_port=htons(PORT);
    s_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    int ret;
    ret=bind(sockfd,(struct sockaddr*)&s_addr,len);
    if(ret<0)
    {
        perror("bind error\n");
        exit(1);
    }
    ret=listen(sockfd,20);
     if(ret<0)
    {
        perror("listen error\n");
        exit(1);
    }
    return sockfd;
}

void set_noblock(int fd)
{
    int flag;
    flag= fcntl(fd,F_GETFL);
    flag|=O_NONBLOCK;
    fcntl(fd,F_SETFL,flag);
}
int read_noblock(int fd,char *msg,size_t size)
{
    int r_n;
    while(r_n=read(fd,msg,size))
    {
        if(r_n<0)
        {
        if(errno!=EAGAIN&&errno!=EWOULDBLOCK&&errno!=EINTR)
        {
            perror("read error\n");
            exit(1);
        }
        continue;
        }
        if(r_n >= 0)
        {
            break;
        }
    
}
    return r_n;
}
